package longrise.phone.com.bjjt_henan.myaccident;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.LFView;
import com.longrise.android.listview_library_refrush.PullToRefreshBase;
import com.longrise.android.listview_library_refrush.PullToRefreshListView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Adapter.AccidentAdapter;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.compensate.AccidentCheckView;
import longrise.phone.com.bjjt_henan.compensate.BankCardInfoView;
import longrise.phone.com.bjjt_henan.compensate.CheckLossReportView;
import longrise.phone.com.bjjt_henan.compensate.CreateAgreementView;
import longrise.phone.com.bjjt_henan.compensate.EvaluateView;
import longrise.phone.com.bjjt_henan.compensate.InsuranceReportChoiceView;
import longrise.phone.com.bjjt_henan.compensate.NewAccidentLoadPicView;
import longrise.phone.com.bjjt_henan.compensate.NewLossLoadPicView;
import longrise.phone.com.bjjt_henan.compensate.NewSelectAccidentView;
import longrise.phone.com.bjjt_henan.compensate.SingleAccidentLoadingView;
import longrise.phone.com.bjjt_henan.main.ServiceCenterView;

/**
 * 事故刷新列表
 */
public class AccidentListView extends LFView implements View.OnClickListener {

    private Context mContext;

    private View mView;

    private PullToRefreshListView mListView;

    private AccidentAdapter mAdapter;

    private boolean isLoading = false;// 正在刷新

    private EntityBean[] beanLists;

    private int caseType;//0查询未完成；1查询已完成

    private BaseApplication application;

    private TextView emptyIV;//无数据时的背景色

    public AccidentListView(Context context, int type) {
        super(context);
        this.mContext = context;
        this.caseType = type;
    }

    @Override
    public View getView() {
        return mView;
    }

    @Override
    public void init() {
        if (null == mContext) {
            return;
        }
        mView = LayoutInflater.from(mContext).inflate(R.layout.view_accidenttlist, null);
        if (mView == null) {
            return;
        }
        emptyIV = (TextView) mView.findViewById(R.id.empty_tv);
        if (caseType == 0) {
            emptyIV.setText("您没有处理中的事务");
        } else {
            emptyIV.setText("您没有已完成的事务");
        }
        mListView = (PullToRefreshListView) mView.findViewById(R.id.pulltorefresh_listview);
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        // 刚拉时的提示
        mListView.getLoadingLayoutProxy().setPullLabel("加载列表数据...");
        // 正在刷新提示
        mListView.getLoadingLayoutProxy().setRefreshingLabel("正在载入...");
        // 拉倒一定高度的提示
        mListView.getLoadingLayoutProxy().setReleaseLabel("放开以刷新...");
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!isLoading) {
                    loadData();
                }
            }
        });
        //设置适配器
        mAdapter = new AccidentAdapter(mContext, caseType);
        if (caseType == 0) {
            mAdapter.setOnClickListner(this);
        }
        mAdapter.setData(beanLists);
        mListView.setAdapter(mAdapter);
        //设置点击事件
        setOnItemClickListener(true);

        application = ((MainActivity) mContext).getAppData();
    }

    @Override
    public void onClick(View v) {
        EntityBean bean = (EntityBean) v.getTag();
        String state = bean.getString("state");
        if (TextUtils.equals(state, "1") || TextUtils.equals(state, "7") || TextUtils.equals(state, "9")
                || TextUtils.equals(state, "10") || TextUtils.equals(state, "14")) {
            checkTime(bean, "1");
        } else if (TextUtils.equals(state, "2") || TextUtils.equals(state, "3") || TextUtils.equals(state, "8")
                || TextUtils.equals(state, "11") || TextUtils.equals(state, "12") || TextUtils.equals(state, "13")
                || TextUtils.equals(state, "19")) {
            checkTime(bean, "2");
        } else {
            dealCase(bean);
        }
    }

    //继续处理历史案件
    private void dealCase(EntityBean bean) {
        String state = bean.getString("state");
        String appcaseno = bean.getString("appcaseno");
        LFView dealView = null;
        if (TextUtils.equals("1", state)) {//等待定责
            dealView = new AccidentCheckView(mContext, appcaseno, 2);
        } else if (TextUtils.equals("2", state)) {//保险报案
            loadDetailInfo(bean, 2);
        } else if (TextUtils.equals("3", state)) {//等待理赔
            dealView = new AccidentCheckView(mContext, appcaseno, 3);
        } else if (TextUtils.equals("4", state)) {//等待评价
            String carno = bean.getString("casecarno");
            dealView = new EvaluateView(mContext, appcaseno);
        } else if (TextUtils.equals("7", state)) {//审核定责照片
            dealView = new AccidentCheckView(mContext, appcaseno, 0);
        } else if (TextUtils.equals("8", state)) {//审核定损照片
            dealView = new AccidentCheckView(mContext, appcaseno, 1);
        } else if (TextUtils.equals("9", state)) {//案件信息未上传
            loadCarInfo(bean);
        } else if (TextUtils.equals("10", state)) {//未生成协议书
            loadDetailInfo(bean, 10);
        } else if (TextUtils.equals("11", state)) {//定损审核（定损报告书）
            loadDetailInfo(bean, 11);
        } else if (TextUtils.equals("12", state)) {//未上传银行卡信息
            loadDetailInfo(bean, 12);
        } else if (TextUtils.equals("13", state)) {//定损图片未上传
            String isSingle = bean.getString("casetype");
            loadPasImg(appcaseno, isSingle, "2");
        } else if (TextUtils.equals("14", state)) {//定责图片未上传
            String isSingle = bean.getString("casetype");
            loadPasImg(appcaseno, isSingle, "1");
        } else if (TextUtils.equals("19", state)) {//理赔中心
            loadDetailInfo(bean, 19);
        }
        if (null != dealView) {
            FrameworkManager.getInstance().showNewForm(mContext, dealView);
            DialogUtils.closeDialog();
        }
    }

    //判断值班时间
    private void checkTime(final EntityBean caseBean, String type) {
        String uid = application.getKckpName();
        String token = application.getToken();
        DialogUtils.showDialog(mContext);
        ApiImpI.getInstance(mContext.getApplicationContext()).checkTimeIsWork(uid, token, type, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
                UiUtil.showToast(mContext, error);
            }

            @Override
            public void onSuccess(Object result) {
                if (mView == null) {
                    return;
                }
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals(restate, "1")) {
                    EntityBean dataBean = bean.getBean("data");
                    if (dataBean != null) {
                        String isTrue = dataBean.getString("istrue");
                        if (TextUtils.equals(isTrue, "1")) {//允许时间内
                            dealCase(caseBean);
                            return;
                        }
                    }
                }
                DialogUtils.closeDialog();
                String redes = bean.getString("redes");
                UiUtil.showToast(mContext, redes);
            }
        });
    }

    private void setOnItemClickListener(boolean flag) {
        if (null != mListView) {
            if (!flag) {
                mListView.setOnItemClickListener(null);
                return;
            }
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    try {
                        if (position < 1) {
                            return;
                        }
                        loadDetailInfo(beanLists[position - 1], 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    //下载案件详情
    private void loadDetailInfo(final EntityBean caseBean, final int type) {
        final String casenumber = caseBean.getString("casenumber");
        EntityBean baseBean = application.getLoginInfo().getBean("userinfo");
        String phone = baseBean.getString("mobilephone");
        String username = application.getKckpName();
        String token = application.getToken();
        DialogUtils.showDialog(mContext);
        ApiImpI.getInstance(mContext.getApplicationContext()).accidentDetails(casenumber, phone, username, token,
                new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        DialogUtils.closeDialog();
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(getContext(), error);
                        }
                    }

                    @Override
                    public void onSuccess(Object result) {
                        DialogUtils.closeDialog();
                        if (null == mView) {
                            return;
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        if (TextUtils.equals(restate, "1")) {
                            EntityBean dataBean = bean.getBean("data");
                            EntityBean[] infoBeans = dataBean.getBeans("casecarlist");
                            String appcaseno = caseBean.getString("appcaseno");
                            String isSingle = caseBean.getString("casetype");
                            LFView dealView = null;
                            if (type == 0) {//进入事故详情界面
                                dealView = new AccidentDetailView(mContext, caseBean, dataBean);
                            } else if (type == 2) {//进入保险报案选择界面
                                dealView = new InsuranceReportChoiceView(mContext, infoBeans, appcaseno);
                                String flag = dataBean.getString("needtype");
                                ((InsuranceReportChoiceView) dealView).setFlag(flag);
                                ((InsuranceReportChoiceView) dealView).setIfSingle(isSingle);
                            } else if (type == 10) {//生成协议书界面
                                String type = dataBean.getString("disposetype");
                                dealView = new CreateAgreementView(mContext, infoBeans, appcaseno, type);
                            } else if (type == 11) {//定损报告书界面
                                dealView = new CheckLossReportView(mContext, infoBeans, appcaseno);
                                ((CheckLossReportView) dealView).setUnqualifylist(isSingle);
                            } else if (type == 12) {//银行卡信息界面
                                if (TextUtils.equals("0", isSingle)) {//单车流程
                                    dealView = new BankCardInfoView(mContext, infoBeans, appcaseno, "0");
                                } else {
                                    dealView = new BankCardInfoView(mContext, infoBeans, appcaseno);
                                }
                            } else if (type == 19) {//理赔中心
                                dealView = new ServiceCenterView(mContext, appcaseno, infoBeans, isSingle);
                            }
                            if (null != dealView) {
                                FrameworkManager.getInstance().showNewForm(mContext, dealView);
                            }
                        } else {
//                            String redes = bean.getString("redes");
                            String redes = "该案件无办理详情！";
                            UiUtil.showToast(mContext, redes);
                        }
                    }
                });
    }

    //获取车辆信息
    private void loadCarInfo(final EntityBean caseBean) {
        EntityBean userInfo = application.getLoginInfo().getBean("userinfo");
        String userName = application.getKckpName();
        String carownername = userInfo.getString("name");
        String token = application.getToken();
        DialogUtils.showDialog(mContext);
        ApiImpI.getInstance(mContext.getApplicationContext()).getCarOwner(carownername, userName, token, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(getContext(), error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                DialogUtils.closeDialog();
                if (null == mView) {
                    return;
                }
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals(restate, "1")) {
                    EntityBean cardBean = bean.getBean("data");
                    String appcaseno = caseBean.getString("appcaseno");
                    String isSingle = caseBean.getString("casetype");
                    LFView dealView = null;
                    if (TextUtils.equals("0", isSingle)) {//单车事故上传
                        dealView = new SingleAccidentLoadingView(mContext, appcaseno, cardBean);
                    } else {
                        //选择事故类型界面-->填写事故信息-->有无争议界面
                        dealView = new NewSelectAccidentView(mContext, appcaseno, cardBean);
                    }
                    if (null != dealView) {
                        FrameworkManager.getInstance().showNewForm(mContext, dealView);
                    }
                } else {
                    String redes = bean.getString("redes");
                    UiUtil.showToast(mContext, redes);
                }
            }
        });
    }

    //获取定责审核过的图片
    private void loadPasImg(final String appcaseno, final String isSingle, final String imgType) {
        String uid = application.getKckpName();
        String token = application.getToken();
        DialogUtils.showDialog(mContext);
        ApiImpI.getInstance(mContext.getApplicationContext()).getPasImgUrl(uid, token, appcaseno, imgType, new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        DialogUtils.closeDialog();
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(mContext, error);
                        }
                    }

                    @Override
                    public void onSuccess(Object result) {
                        DialogUtils.closeDialog();
                        if (null == mView) {
                            return;
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        if (TextUtils.equals(restate, "1")) {
                            EntityBean dataBean = bean.getBean("data");
                            int flag = 0;
                            EntityBean[] unBeans = null;
                            EntityBean[] isBeans = null;
                            if (null != dataBean) {
                                flag = 1;
                                unBeans = dataBean.getBeans("notpasslist");
                                isBeans = dataBean.getBeans("passlist");
                            }
                            if (TextUtils.equals(imgType, "1")) {
                                NewAccidentLoadPicView view = new NewAccidentLoadPicView(mContext, appcaseno, flag);
                                view.setUnqualifylist(unBeans);
                                view.setIsqualifylist(isBeans);
                                view.setCaseType(isSingle);
                                view.setIsHistroy(true);
                                FrameworkManager.getInstance().showNewForm(mContext, view);
                            } else if (TextUtils.equals(imgType, "2")) {
                                NewLossLoadPicView dealView = new NewLossLoadPicView(mContext, appcaseno, flag);
                                dealView.setUnqualifylist(unBeans);
                                dealView.setIsqualifylist(isBeans);
                                dealView.setCaseType(isSingle);
                                dealView.setIsHistroy(true);
                                FrameworkManager.getInstance().showNewForm(mContext, dealView);
                            }
                            return;
                        }
                        String error = bean.getString("redes");
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(mContext, error);
                        }
                    }
                }
        );
    }

    //加载数据
    public void loadData() {
        EntityBean baseBean = application.getLoginInfo().getBean("userinfo");
        String userId = baseBean.getString("id");
        String phone = baseBean.getString("mobilephone");
        String token = application.getToken();
        ApiImpI.getInstance(mContext.getApplicationContext()).searchAllCase(userId, phone, String.valueOf(caseType), token,
                new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        if (null != mListView) {// 停止刷新
                            mListView.onRefreshComplete();
                        }
                        DialogUtils.closeDialog();
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(mContext, error);
                        }
                    }

                    @Override
                    public void onSuccess(Object result) {
                        if (null == mListView) {// 停止刷新
                            return;
                        }
                        mListView.onRefreshComplete();
                        DialogUtils.closeDialog();
                        beanLists = null;//重置数据
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        if (TextUtils.equals("1", restate)) {
                            beanLists = bean.getBeans("data");
                        }
                        if (null == beanLists || beanLists.length <= 0) {
                            mListView.setEmptyView(emptyIV);
                        } else {
                            emptyIV.setVisibility(View.GONE);//null
                        }
                        if (null != mAdapter) {
                            mAdapter.setData(beanLists);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    @Override
    public void refresh() {
        if (!isLoading) {
            DialogUtils.showDialog(mContext);
            loadData();
        }
    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        setOnItemClickListener(false);
        mView = null;
        if (null != mListView) {
            mListView.setAdapter(null);
        }
        mListView = null;
        mAdapter = null;
        beanLists = null;
        DialogUtils.destroyDialog();
    }
}

